package io.valuesfeng.picker;

import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;

import com.afollestad.materialdialogs.MaterialDialog;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import io.valuesfeng.picker.adapter.ImageGridViewAdapter;
import io.valuesfeng.picker.engine.GlideEngine;
import io.valuesfeng.picker.utils.PicturePickerUtils;
import io.valuesfeng.picker.utils.compressor.Compressor;

/**
 * Created by Dune on 16/8/14.
 */
public class ImageGridViewManage implements AdapterView.OnItemClickListener {

    public static final int REQUEST_CODE_CHOOSE = 9876;
    private GridView mGridView;
    private Fragment mFragment;
    private List<Uri> mUris = new ArrayList<>();
    private List<String> images = new ArrayList<>();
    private ImageGridViewAdapter mImageGridViewAdapter;
    private int maxCount;
    private Compressor mCompressor;
    private MaterialDialog materialDialog;
    private CompressImageTask mCompressImageTask;


    public ImageGridViewManage(GridView gridView, Fragment fragment, int maxCount) {
        mGridView = gridView;
        mFragment = fragment;
        this.maxCount = maxCount;
        init();
    }

    private void init() {

        mImageGridViewAdapter = new ImageGridViewAdapter(mFragment, maxCount, mUris);
        mGridView.setAdapter(mImageGridViewAdapter);
        mGridView.setOnItemClickListener(this);
        mCompressor = new Compressor.Builder(mFragment.getContext()).build();
    }


    public void setOnActivityResult(Intent intent) {

        mUris = PicturePickerUtils.obtainResult(intent);
        materialDialog = new MaterialDialog.Builder(mFragment.getActivity())
                .content(R.string.load_image_hint)
                .progress(true, 0)
                .show();

        mCompressImageTask = new CompressImageTask(this);
        Uri[] a = new Uri[mUris.size()];
        mCompressImageTask.execute(mUris.toArray(a));

    }


    public List<String> getImages() {

        return images;
    }

    public void deleteItemImage(int position) {
        mUris.remove(position);
        images.remove(position);
        mImageGridViewAdapter.notifyDataSetChanged();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {

        if (mImageGridViewAdapter.getImageCount() == position) {
            Picker.from(mFragment)
                    .count(maxCount)
                    .resume(mUris)
                    .enableCamera(true)
                    .setEngine(new GlideEngine())
                    .forResult(REQUEST_CODE_CHOOSE);
        } else {
            new MaterialDialog.Builder(mFragment.getActivity()).title(R.string.dlg_select_title)
                    .items(R.array.dlg_image_operation)
                    .itemsCallback(new MaterialDialog.ListCallback() {
                        @Override
                        public void onSelection(MaterialDialog dialog, View itemView, int dlgPosition, CharSequence text) {

                            switch (dlgPosition) {
                                case 0:
                                    PreviewImageActivity.startActivity(mFragment.getActivity(), getImages(), position, false);
                                    break;
                                case 1:
                                    deleteItemImage(position);
                                    break;
                            }
                        }
                    })
                    .show();
        }
    }

    public String getRealPathFromURI(Uri contentUri) {
        String res = null;
        String[] p = {MediaStore.Images.Media.DATA};
        Cursor cursor = mFragment.getActivity().getContentResolver().query(contentUri, p, null, null, null);
        if (cursor != null) {

            if (cursor.moveToFirst()) {
                int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                res = cursor.getString(column_index);
            }
            cursor.close();
            return res;
        }
        return null;
    }

    public void compressorSuccessful(List<String> images) {

        if (materialDialog != null && materialDialog.isShowing()) {

            materialDialog.dismiss();
        }
        mImageGridViewAdapter.setData(mUris);
        this.images = images;
    }

    public String compressorImage(String path) {

        if (path != null) {

            return mCompressor.compressToFile(new File(path)).getPath();
        }
        return null;
    }


    static class CompressImageTask extends AsyncTask<Uri, Void, List<String>> {

        private ImageGridViewManage mImageGridViewManage;

        public CompressImageTask(ImageGridViewManage imageGridViewManage) {
            mImageGridViewManage = imageGridViewManage;
        }

        @Override
        protected List<String> doInBackground(Uri... params) {

            List<String> images = new ArrayList<>();
            for (Uri uri : params) {

                String path = mImageGridViewManage.getRealPathFromURI(uri);
                try {

                    images.add(mImageGridViewManage.compressorImage(path));
                } catch (IllegalArgumentException e) {
                    images.add(path);
                }

            }
            return images;
        }

        @Override
        protected void onPostExecute(List<String> images) {
            super.onPostExecute(images);

            mImageGridViewManage.compressorSuccessful(images);

        }
    }


    public void destroy() {

        if (mCompressImageTask != null &&
                mCompressImageTask.getStatus() != AsyncTask.Status.FINISHED) {
            mCompressImageTask.cancel(true);
        }
        mFragment = null;
    }
}

